<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class SecurityController extends ApiController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function editPass(){
        $oldpassword = $this->request->input('oldpassword');
        $newpassword = $this->request->input('newpassword');

        $user = Auth::user();
        if ($user->getAuthPassword() == Hash::make($oldpassword)) {
            $user->update([
                'password'=>Hash::make($newpassword)
            ]);
            return ajaxReturn();
        }

        if ($user->getAuthPassword() == sha1(md5($oldpassword))) {
            $user->update([
                'password'=>Hash::make($newpassword)
            ]);
            return ajaxReturn();
        }

        return ajaxError(1, trans('member.password incorrect'));
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindMobile() {
        $mobile = $this->request->input('mobile');
        $user = User::where([['uid', '<>', $this->uid],['mobile', '=', $mobile]])->first();
        if ($user) {
            return ajaxError(1, trans('member.mobile be occupied'));
        }else {
            Auth::user()->update(['mobile'=>$mobile]);
            return ajaxReturn();
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindEmail() {
        $email = $this->request->input('email');
        $user = User::where([['uid', '<>', $this->uid],['email', '=', $email]])->first();
        if ($user) {
            return ajaxError(1, trans('member.email be occupied'));
        }else {
            Auth::user()->update(['email'=>$email]);
            return ajaxReturn();
        }
    }
}
